package com.fzu.ess.common.service.Impl;

import com.fzu.ess.common.Const;
import com.fzu.ess.common.Model.JsonModel;
import com.fzu.ess.common.service.MailService;
import com.fzu.ess.common.utils.PathUtils;
import com.fzu.ess.sys.shiro.SpringCacheManagerWrapper;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.codec.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.UUID;

/**
 * Created by ercha on 2015/10/28.
 */
@Service
public class MailServiceImpl implements MailService{

    private Cache<String, String> mailCache;

    private JavaMailSenderImpl senderImpl = null;
    private String sendFrom = null;

    @Autowired
    public MailServiceImpl(SpringCacheManagerWrapper shiroCacheManager){
        mailCache = shiroCacheManager.getCache(Const.CACHE_NAME.MAIL);

        senderImpl = new JavaMailSenderImpl();

        Properties properties = new Properties();
        InputStream in = MailServiceImpl.class.getResourceAsStream("/config.properties");
        try{
            properties.load(in);
            senderImpl.setHost(properties.getProperty("mail.host").trim());
            senderImpl.setUsername(properties.getProperty("mail.username").trim());
            senderImpl.setPassword(properties.getProperty("mail.password").trim());
            Properties sendProps = new Properties();
            sendProps.put("mail.smtp.auth", properties.getProperty("mail.smtp.auth").trim());
            sendProps.put("mail.smtp.timeout", properties.getProperty("mail.smtp.timeout").trim());
            senderImpl.setJavaMailProperties(sendProps);

            sendFrom = properties.getProperty("mail.sendFrom").trim();
        } catch(IOException e){
            e.printStackTrace();
        }
    }

    public void sendSimpleMail(String sendTo, String subject, String text){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(sendFrom);
        simpleMailMessage.setTo(sendTo);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(text);

        senderImpl.send(simpleMailMessage);
    }

    public boolean sendHtmlMail(String sendTo, String subject, String text){
        MimeMessage mimeMessage = senderImpl.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, "UTF-8");
        try {
            mimeMessageHelper.setFrom(sendFrom);
            mimeMessageHelper.setTo(sendTo);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText("<html><head></head><body>" + text + "</body></html>", true);
            senderImpl.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public JsonModel sendActiveMail(String email){
        JsonModel jsonModel = new JsonModel();
        if(email==null || email.length()<1){
            return jsonModel;
        }

        try {
            String baseUrl = PathUtils.getBaseUrl();
            UUID uuid = UUID.randomUUID();
            String code = Base64.encodeToString(email.getBytes());
            StringBuffer activeUrl = new StringBuffer().append(baseUrl)
                    .append("/active?uuid=").append(uuid).append("&code=").append(code);

            //发送验证邮件
            boolean ret = sendHtmlMail(email, "二手书信息网",
                    "感谢您注册二手书信息网！<br/><br/>点击链接即可激活账号：<a href='" + activeUrl + "'>" + activeUrl + "</a><br/><br/>" +
                            "如果不是您本人进行的操作，您不需要进行任何操作。<br/><br/>您也可以点击这里进入我们的首页：");

            jsonModel.setSuccess(ret);

            //将 uuid 和 email 放入缓存
            mailCache.put(uuid.toString(), email);
        }catch (Exception e){
            e.printStackTrace();
            jsonModel.setSuccess(false);
        }
//        System.out.println("uuid: " + uuid.toString() + "\n\n");
//        System.out.println("cache: " + mailCache.get(uuid.toString()) + "\n\n");
        return jsonModel;
    }

    @Override
    public JsonModel sendForgetPasswordMail(String email) {
        JsonModel jsonModel = new JsonModel();

        if(email==null || email.length()<1){
            return jsonModel;
        }

        try {
            String baseUrl = PathUtils.getBaseUrl();
            UUID uuid = UUID.randomUUID();
            String code = Base64.encodeToString(email.getBytes());
            StringBuffer activeUrl = new StringBuffer().append(baseUrl)
                    .append("/resetPassword?uuid=").append(uuid).append("&code=").append(code);

            boolean ret = sendHtmlMail(email, "二手书信息网",
                    "二手书信息网：<br/><br/>您正在尝试重置密码，点击链接即可重置密码：<a href='" + activeUrl + "'>" + activeUrl + "</a><br/><br/>" +
                            "如果不是您本人进行的操作，您不需要进行任何操作。<br/><br/>");

            jsonModel.setSuccess(ret);

            //将 uuid 和 email 放入缓存
            mailCache.put(uuid.toString(), email);
        }catch (Exception e){
            e.printStackTrace();
            jsonModel.setSuccess(false);
        }
        return jsonModel;
    }

    @Override
    public JsonModel sendResetPasswordMail(String email, String password) {
        JsonModel jsonModel = new JsonModel();

        if(email==null || email.length()<1){
            return jsonModel;
        }

        try {
            String baseUrl = PathUtils.getBaseUrl();
            UUID uuid = UUID.randomUUID();
            String code = Base64.encodeToString(email.getBytes());
            StringBuffer activeUrl = new StringBuffer().append(baseUrl)
                    .append("/resetPassword?uuid=").append(uuid).append("&code=").append(code);

            boolean ret = sendHtmlMail(email, "二手书信息网",
                    "二手书信息网：<br/><br/>您的新密码为：" + password + "<br/><br/>" +
                            "请尽快修改密码！<br/><br/>");

            jsonModel.setSuccess(ret);

        }catch (Exception e){
            e.printStackTrace();
            jsonModel.setSuccess(false);
        }
        return jsonModel;
    }

    @Override
    public String hasMail(String uuid, String code) {
        if(uuid==null || code==null){
            return null;
        }

        String email = Base64.decodeToString(code);

        try {
            String c = mailCache.get(uuid);
            if(c==null){
                return null;
            }
            System.out.print("c: " + c + "\n");
            return c.equals(email) ? email : null;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
